/**
  * Created by Joshua Conero(O'Uymas) on 2016/12/21 0021.
  * QQ: 957376074
  * E-mail: Brximl@163.com
  */
/*
package org.yang
package Tools
*/
package org.yang.Tools
import java.awt.{Color, Dimension}
import java.io.File
import scala.swing.FileChooser.SelectionMode
import scala.swing._
import scala.swing.event.{ButtonClicked, EditDone}
import org.yang.Common
import com.alibaba.fastjson._
import scala.collection.mutable.ArrayBuffer
import scala.swing.Swing._
import conero.dateDiff
class DirHelper {
  // MainFrame -
  val helper = new Common
  val saveName = "tools.dirhelper"
  var dirRuningMark = false   // 执行标签
  val tipLabel = new Label("等在就绪..."){
    horizontalAlignment = Alignment.Left
  }  // 进度提示
  new Frame {
    title = "目录比较工具"
    background = Color.red
    preferredSize = new Dimension(400, 400)
    var lastDir = historyReport("dir")  // 获取历史记录
    lastDir = if(lastDir == "") "." else helper.base64_decode(lastDir)
    val dir_choseer = new FileChooser(new File(lastDir)){
      fileSelectionMode = SelectionMode.DirectoriesOnly
    }
    val dir_btn = new Button("目录"){
      horizontalAlignment = Alignment.Left
    }
    val dir_ipt = new TextField(20){
      horizontalAlignment = Alignment.Left
    }
    val console = new BoxPanel(Orientation.Vertical){
      preferredSize = new Dimension(800, 600)
      /*
      val table = new Table(Array(List("","","","","","").toArray).asInstanceOf[Array[Array[Any]]],Array("名称", "类型", "遍历次数", "文件夹数","文件数", "文件大小").asInstanceOf[Array[Any]]){
        preferredViewportSize = new Dimension(500, 400)
      }
      contents += new ScrollPane(table)
      */
    }
    val topComp = new BoxPanel(Orientation.Vertical){
      preferredSize = new Dimension(400,100)
      border = CompoundBorder(TitledBorder(EtchedBorder, "url输入选项"), EmptyBorder(5,100,20,300))
      contents += new Label("选择/输入目录"){
        horizontalAlignment = Alignment.Left
      }
      contents += dir_ipt
      contents += dir_btn
      contents += tipLabel
    }
    contents = new BoxPanel(Orientation.Vertical){
      contents += topComp
      contents += console
      listenTo(dir_btn,dir_ipt)
      reactions += {
        case ButtonClicked(`dir_btn`) =>
          dir_choseer.showDialog(this,"确定")
          val path = dir_choseer.selectedFile.getPath   // 获取文件选择结果
          dir_ipt.text = path
          if(path != "") dirCheck(path,console)
        case EditDone(`dir_ipt`) =>
          val path = dir_ipt.text
          if(path != "" && helper.is_dir(path) == true){
            dirCheck(path,console)
          }
          else{
            if(path != "") tipLabel.text = "文件夹目录无效"
          }
      }
    }
    visible = true
  }
  // 文件运行
  def dirCheck(path:String,panel:BoxPanel):Unit = {
    if(path == "") return
    val rpt = new dateDiff()
    dirRuningMark = true
    runTimeTip()
    //helper.historyJson(saveName,Array(path))
    helper.historyReport(saveName,helper.map2JsonStr(Map("dir" -> helper.base64_encode(path))))
    val curDir = new File(path)
    val fls = curDir.listFiles()
    val br = "\r\n"
    val model = new ArrayBuffer[Array[String]]
    var count = 0
    var dirCount = 0
    var fileCount = 0
    var sizeCount = 0
    for(f<- fls){
      if(f.isDirectory){
        val dirname = f.getAbsolutePath
        val retMap = dirEach(dirname)
        count = count + retMap("count")
        dirCount = dirCount + retMap("sizeCount")
        fileCount = fileCount + retMap("fileCount")
        sizeCount = sizeCount + retMap("sizeCount")
        model += Array(dirname,"目录",retMap("count").toString,retMap("dirCount").toString,retMap("fileCount").toString,helper.bitSize(retMap("sizeCount").toLong))
      }
      else{
        println("文件：",f.getAbsolutePath)
        model += Array(f.getAbsolutePath,"文件","1","0","1",helper.bitSize(f.length()))
        count = count + 1
        fileCount = fileCount + 1
        sizeCount = sizeCount + f.length().toInt
      }
    }
    /*
    val md = Array(List("Mary", "Campione", "Snowboarding", 5, false).toArray,
      List("Alison", "Huml", "Rowing", 5, false).toArray,
      List("Kathy", "Walrath", "Knitting", 5, false).toArray,
      List("Sharon", "Zakhour", "Speed reading", 5, false).toArray,
      List("Sharon", "Zakhour", "Speed reading", 5, false).toArray,
      List("Philip", "Milne", "Pool", 5, false).toArray)
    val table = new Table(md, Array("First Name", "Last Name", "Sport", "# of Years", "Vegetarian")) {
      preferredViewportSize = new Dimension(500, 70)
    }
    */

    // val table = new Table(model,Array("名称", "类型", "遍历次数", "文件个数", "文件大小")) 编译不通过
    // val table = new Table(model.asInstanceOf[Array[Array[Any]]],Array("名称", "类型", "遍历次数", "文件个数", "文件大小").asInstanceOf[Array[Any]]) // 编译通过运行不通过
    val modelArray = model.toArray
    val table = new Table(modelArray.asInstanceOf[Array[Array[Any]]],Array("名称", "类型", "遍历次数", "文件夹数","文件数", "文件大小").asInstanceOf[Array[Any]]){
      preferredViewportSize = new Dimension(500, 400)
    }
    panel.contents += new ScrollPane(table)
    // 完成后的报告
    val rptText = "本次读取数据用时： "+rpt.diffTime()+" ms，时间： "+helper.sysdate +
      "扫描总次数： "+count.toString+"，共扫描文件数："+fileCount.toString+",文件夹数:"+dirCount.toString+",文件大小："+helper.bitSize(sizeCount.toLong)
    panel.contents += new Label(rptText)
    runTimeTip("quit")
  }
  // 递归遍历目录下的文件
  def dirEach(dir:String):Map[String,Int] ={
    val path = new File(dir)
    val fls = path.listFiles()
    var fileCount = 0
    var dirCount = 0
    var count = 0
    var sizeCount:Long = 0  // 声明为Long 类型
    for(f<- fls){
      count = count +1
      if(f.isFile){
        fileCount = fileCount + 1
        sizeCount = sizeCount + f.length()
      }
      else{
        dirCount = dirCount + 1
        val retMap = dirEach(f.getAbsolutePath)
        count = count + retMap("count")
        dirCount = dirCount + retMap("dirCount")
        fileCount = fileCount + retMap("fileCount")
        sizeCount = sizeCount + retMap("sizeCount").toLong
      }
    }
    //Array(count,fileCount,sizeCount.toInt)
    Map("count"->count,"fileCount"->fileCount,"dirCount"->dirCount,"sizeCount"->sizeCount.toInt)
  }
  // 目录历史记录操作
  def historyReport(key:String=""):String = {
    val str = helper.historyReport(saveName)
    if(key == "") return str
    if(str != ""){
      val json = JSON.parseObject(str)
      return json.get(key).toString
    }
    ""
  }
  // 内容提示框
  def runTimeTip(cmd:String = ""):Unit = {
    if(cmd == ""){
      var count = 1
      // 死循环
      while (false) {
        tipLabel.text = "..."+count.toString+"..."
        count = count + 1
      }
    }else{
      tipLabel.text = ""
    }
  }
}
